package com.cgycms.prototype.config;

import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import com.cgycms.prototype.SitePrototypeService;
import com.cgycms.prototype.entity.SiteEntity;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * @author: 超哥呦
 * @Description: 拦截器配置、静态目录映射
 * @date: 2021/11/13 23:31
 **/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private SitePrototypeService sitePrototypeService;

    private static final String ALL_PATH = "/**";

    @Bean
    public WebPrototypeInterceptor viewInterceptor() {
        return new WebPrototypeInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        SiteEntity siteEntity = sitePrototypeService.querySite();
        String path = siteEntity.getPreviewName() + ALL_PATH;
        registry.addInterceptor(new SaRouteInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(path)
                .excludePathPatterns("/userManager/doLogin")
                .excludePathPatterns("/view/**")
                .excludePathPatterns("/error")
                .excludePathPatterns("/favicon.ico")
                .excludePathPatterns("/static/**")
                .excludePathPatterns("/index")
                .excludePathPatterns("/")
                .excludePathPatterns("/initSite")
                .excludePathPatterns("/404");

        registry.addInterceptor(viewInterceptor())
                .addPathPatterns(path);
    }


    /**
     * 处理静态映射目录设置
     * 系统兼容-正确预览路径： /view/**
     * 系统兼容-正确解压路径： D:/unzip/
     * 系统兼容-正确存储路径：D:/data/
     * 但注意!!!
     * 数据库中配置需要不带结尾，程序会自动处理   '/' or '/**'
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        SiteEntity siteEntity = sitePrototypeService.querySite();
        String diskName = siteEntity.getDiskName();
        String zipOutName = siteEntity.getZipOutName();
        String previewName = siteEntity.getPreviewName();
        String suffix = "/";
        if (!diskName.endsWith(suffix)) {
            diskName += suffix;
        }
        if (!zipOutName.endsWith(suffix)) {
            zipOutName += suffix;
        }
        if (previewName.endsWith(suffix)) {
            previewName = previewName.substring(0, previewName.length() - 1) + ALL_PATH;
        } else {
            previewName += ALL_PATH;
        }
        registry.addResourceHandler(previewName).addResourceLocations("file:" + diskName).addResourceLocations("file:" + zipOutName);
    }

}
